# coding=utf-8
"""
    脚本
"""

import os
from flask import Blueprint, render_template, request, url_for, jsonify

from app.conf.err_msg import ErrClass
from utils.do_log import c_log
from utils.do_path import CODE_FOLDER

# @Time    : 2025/1/7 11:09
# @Author  : ginger
# @Email   : gingerqgyy@outlook.com
# @Project : curl_conversion
# @File    : view_codes.py

code = Blueprint('code', __name__, template_folder='templates')


def code_file_list():
    # codes = [{'title': file_name[:-3:]} for file_name in os.listdir(CODE_FOLDER) if not file_name.startswith('__init__') and file_name.endswith('.py')]
    codes = [{'title': file_name} for file_name in os.listdir(CODE_FOLDER) if not file_name.startswith('test_')]
    return codes


def code_file_name_list():
    # codes = [file_name[:-3:] for file_name in os.listdir(CODE_FOLDER) if not file_name.startswith('__init__') and file_name.endswith('.py')]
    codes = [file_name for file_name in os.listdir(CODE_FOLDER) if not file_name.startswith('test_')]
    return codes


@code.route('codes', methods=['GET', 'POST', ])
def show_coeds():
    codes = code_file_list()
    return render_template('show_codes.html', codes=codes)


@code.route('get_code_info', methods=['GET', 'POST', ])
def code_info():
    title = request.form['title']
    c_log.info(f'请求参数 : {title}')

    # 异常情况处理 :
    if not title:
        return render_template('err_msg.html', err_msg=f'{ErrClass.no_code_file}')
    if title not in code_file_name_list():
        return render_template('err_msg.html', err_msg=f'{ErrClass.not_code_file}')

    # 清理文件名以防止路径遍历攻击 :
    safe_title = title.rsplit('.', 1)[0]
    ext = title.rsplit('.', 1)[-1]
    safe_title = ''.join([c for c in safe_title if c.isalnum() or c in ('_', '-')])
    code_file_name = os.sep.join([CODE_FOLDER, f'{safe_title}.{ext}'])

    # 检查文件是否存在 : ( 正常不会进入该判断, 因为前面已经校验过文件名了 )
    if not os.path.exists(code_file_name):
        return render_template('err_msg.html', err_msg=f'{ErrClass.un_code_file}')

    with open(code_file_name, mode='r', encoding='utf8') as f:
        code_content = f.read()
    return render_template('code_info.html', code_title=safe_title, code_info=code_content)
